package com.ttdc.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ttdc.assist.ErrEnum;
import com.ttdc.assist.Msg;
import com.ttdc.mapper.UserMapper;
import com.ttdc.pojo.User;
import com.ttdc.pojo.UserExample;
import com.ttdc.service.UserService;  
  
@Controller  
public class UserController {  
    @Autowired  
    private UserService userService; 
    private UserMapper userMapper;
    private UserExample example;
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);  
    

	 //注册功能的实现 
	@ResponseBody
	@RequestMapping("/register")
	public Msg Register(String name,String password,Integer phone) {
		//判断该用户名是否已被注册
		boolean num = userService.userRegister(name);
		
		if (num == false) {
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("username", "用户名已被注册");
			return Msg.error().add("map", map2);
		} else {
			User user = new User();
			user.setName(name);
			user.setPassword(password);
			user.setPhone(phone);
			
			//1超级管理员:直接修改数据库的用户，只能打开mySQL改的
			//2普通会员:通过请求注册的用户
			user.setRoleId(3);
			int flag = userService.userInsert(user);
			
			if (flag==1) {
				return Msg.success();
			} else {
				return Msg.error();
			}
		}
	}
    
    
    
	//登录功能的实现 

    @ResponseBody
    @RequestMapping("/login")
    public Msg Login(HttpServletRequest request,HttpServletResponse response,String name, String password,Integer roleId) 
    		throws IOException{
    	System.out.println(roleId);
    	if (name == null || password == null) {
    		response.sendRedirect(request.getContextPath()+"/signin");
    		return Msg.error();
		} else {

			// 根据账号判断数据库中是否存在该用户
			List<User> userList = userService.selectByNameForId(name);
			int rId=userList.get(0).getRoleId();
			
//			System.out.println(rId);
			
			if((int)roleId != rId){
		
	    		return Msg.error().add("errMsg",ErrEnum.ROLE_ERROR.getErrorMessage());
	    		
			}else{
				// 如果不存在该用户
				if (userList.size() == 0) {
					// 返回登录页面
					return Msg.error().add("errMsg", ErrEnum.NAME_LOGIN_ERROR.getErrorMessage());
	
					// 如果存在该用户
				} else {
					
		    		//因为不能有相同的用户名，所以该List<User>只有一个值，可以直接使用获得id值
			    	int intUserId = userList.get(0).getId();
			    	//类型
			    	int intRoleId = userList.get(0).getRoleId();
					// 根据账号和密码判断是否输入的都正确
					int num = userService.selectByNamePassword(name, password);
					 
							// begin:对密码是否正确的判断
							// 如果密码对了
							if (num != 0) {
								//把id保存进session，在后面的文章发表、评论发表时候会用到				    	
								HttpSession session = request.getSession();	
//								session.setAttribute("intRoleId", intRoleId);
//								session.setAttribute("intUserId", intUserId);				    					    	
								//begin:拦截器所需				    	
								session.setAttribute("userList", userList);				    	
								//end:拦截器所需				    	
	
								String url="/index";
								if(rId == 1){
									url="/admin/admin";
								}
								if(rId==2){
									url="/index";
								}
								return Msg.success().add("url", url);
							
							} else {
								return Msg.error().add("errMsg", ErrEnum.PASSWORD_LOGIN_ERROR.getErrorMessage());
							}
							// end:对密码是否正确的判断
					  }
		}		  
				  
					
		}
    
   } 
   //end:login方法
    

	//删除 
	@RequestMapping("/u_delete")	
    public String deleteByPrimaryKey(@RequestParam("id") Integer id,Model model){
       userService.deleteByPrimaryKey(id);
       return "redirect:/u_list";
    }
	
	//查询  可多條件查詢
	@RequestMapping("/u_selectById")
	public String selectByPrimaryKey(User user, Model model){
		example = new UserExample();
		UserExample.Criteria c=example.createCriteria();
		if (user == null) {
			   return "/admin/user";
		} else {
			if (user.getName() != null) {
				// 根據菜系名称查詢
				System.out.println(user.getName());

				c.andNameEqualTo(user.getName());
				List<User> list =userService.selectByExample(example);
				model.addAttribute("list", list);
			}
			 return "/admin/user";
		}
			
	}
	
	//跳转到修改页面，根据id查出来在update那个页面显示
	@RequestMapping("/u_toupdate")
	public String updateByPrimaryKey(Integer id,Model model){
		User list =userService.selectByPrimaryKey(id);
		 model.addAttribute("list",list);
		 return "/admin/updateUser";
		
	}
	//由update修改页面放回结果进行修改，然后返回列表
	@RequestMapping("/u_update")
	public String updateByPrimaryKeySelective( User record){
		userService.updateByPrimaryKey(record);
	       return "redirect:/u_list";
	}
	
	// 用条件查询所有的菜系信息
	@RequestMapping("/u_selectAll")
	public String selectAll(Model model) {
		example = new UserExample();
		UserExample.Criteria c=example.createCriteria();
		c.andIdIsNotNull();
		List<User> list =userService.selectByExample(example);
		model.addAttribute("list", list);
		 return "/admin/user";
	}
	
	
	//查询所有数据
    @RequestMapping("/u_list")
   
    public String selectByAll(Model model){
    	List<User> list = userService.selectByAll();
         model.addAttribute("list",list);
         return "/admin/user";
    }
    
    
}  